# @time     :2022/2/18
# @Author   :Simple
# @FileName :conftest
import os
import time

import allure
import pytest
from allure_commons.types import AttachmentType
from selenium.webdriver.chrome.webdriver import WebDriver

from util.logger import log as logger
from util.device import init_device_info
from util.driver import BaseDriver

driver = None
base_driver = None
device_name = None
udid = None


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    用例失败处截图并保存到报告中
    :param item:
    :return:
    """
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    if report.when == 'call' or report.when == 'setup':
        xfail = hasattr(report, 'wasxfail')
        if(report.skipped and xfail) or (report.failed and not xfail):
            case_path = report.nodeid.replace("::", "-") + ".png"
            if '[' in case_path:
                logger.debug(case_path)
                logger.debug(case_path.split('-')[0])
                case_name = case_path.split('-')[0] + "].png"
            else:
                case_name = case_path
            try:
                screen_img = driver.get_screenshot_as_png()
                allure.attach(screen_img, name=case_name, attachment_type=AttachmentType.PNG)
            except Exception as e:
                logger.error(e)
        report.extra = extra


def pytest_collection_modifyitems(items):
    """
    hook：
    测试用例收集完成时，将收集到的item的name和nodeid的中文显示在控制台上
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")


def pytest_addoption(parser):
    """
    hook：
    注册自定义参数cmdopt、browser_opt到配置对象
    :param parser:
    :return:
    """
    parser.addoption("--cmdopt", action="store", default=None, help="将自定义命令行参数'--cmdopt'添加到pytest配置中")
    parser.addoption("--device_opt", action="store", default=None, help=None)


@pytest.fixture(scope="session")
def cmdopt(request):
    """
    接收命令行传过来的cmdopt值
    """
    return request.config.getoption("--cmdopt")


@pytest.fixture(scope='session')
def device_opt(request):
    """
    接收命令行传过来的browser_opt值
    :param request:
    :return:
    """
    return request.config.getoption("--device_opt")


@pytest.fixture(scope="session")
def common_driver(cmdopt, flag=2):
    """
    启动app、获取driver
    :param cmdopt:
    :param flag:
    :return:
    """
    global driver
    global base_driver
    global device_name
    global udid
    if cmdopt is None:
        cmdopt = init_device_info()[0]
    if isinstance(cmdopt, str):
        cmdopt = eval(cmdopt)

    device_name = cmdopt['device_name']
    udid = cmdopt['udid']
    try:
        base_driver = BaseDriver(cmdopt)
        base_driver.start_appium()
        driver = base_driver.get_driver()
        yield driver
        driver.quit()
        time.sleep(2)
    except:
        flag -= 1
        if flag >= 0:
            common_driver(cmdopt, flag)
    finally:
        base_driver.close_appium()
        print("test end!")

